//
//  ZMGaugeView.m
//  testDemo
//
//  Created by 赵林瑞 on 16/5/14.
//  Copyright © 2016年 RZOL. All rights reserved.
//

#import "ZMGaugeView.h"

#import "UIColor+Extensions.h"
#import "UIView+Extensions.h"

#define degreesToRadians(x) (M_PI*(x)/180.0) //把角度转换成PI的方式
#define w self.frame.size.width
#define h self.frame.size.height
// 位置适配
#define ZMScacle (w/283.f)
#define ZM_SPACE(x) ((x) * ZMScacle)
#define ZM_circle_X w/2.f
#define ZM_circle_Y h - ZM_SPACE(15)
#define ZMScreenWidth [UIScreen mainScreen].bounds.size.width
#define ZMScreenHeight [UIScreen mainScreen].bounds.size.height
#define ZMScreen_scacle (ZMScreenWidth/320.f)
#define ZMScacle (w/283.f)
// 传入色值
#define HEXCOLOR_a(hex,a) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:(a)]
#define HEXCOLOR(hex) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:1]

#define ZM_FONT(x) [UIFont systemFontOfSize:x*ZMScacle]

@interface ZMGaugeView ()
{
    CALayer *layer;
    UILabel *_countLab;
}

@property (nonatomic, strong) UIImageView *bgImageView; // 背景图片
@property(nonatomic) CGFloat currentRadian;
@property (nonatomic, assign) NSInteger count;

@end

@implementation ZMGaugeView

- (UIImageView *)bgImageView {
    
    if (nil == _bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
        
        
        _bgImageView.userInteractionEnabled = NO ;
    }
    return _bgImageView;
}

- (NSInteger)count {
    if (!_count) {
        _count = 13;
    }
    return _count;
}

#pragma mark init stuff

- (id) init
{
    self = [super init];
//    [self setup];
    
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
//        [self setup];
    }
    return self;
}

- (void)setup
{
    self.opaque = NO;
    self.contentMode = UIViewContentModeRedraw;
    
//    if (!self.degree) {
//        self.degree = 12;
//    }
    if (self.degree>=0  &&  self.degree<7) {
        self.currentRadian = - (7-self.degree) * (M_PI/13);
    }else{
        self.currentRadian = (self.degree - 7) * (M_PI/13);
    }
//    self.currentRadian = M_PI/4;
    [self addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width/2.f-25*ZMScacle, self.height*0.35, 50*ZMScacle, 20*ZMScacle)];
    label.text = [NSString stringWithFormat:@"%d 月", (int)self.degree];
    label.font = ZM_FONT(15);
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = HEXCOLOR(0xff4343);
    [self addSubview:label];
    _countLab = label;
    
    self.bgImageView.image = [UIImage imageNamed:@"zhen"];
    self.bgImageView.frame = self.bounds;
    self.bgImageView.backgroundColor = [UIColor clearColor];
    
    [self addSubview:self.bgImageView];
    
    
    CALayer *secondLayer = [CALayer layer];
    // 设置锚点
    secondLayer.anchorPoint = CGPointMake(0.5, 1);
    secondLayer.position = CGPointMake(w*0.5, h-15*ZMScacle);
    secondLayer.backgroundColor = HEXCOLOR(0xff8069).CGColor;
    secondLayer.bounds = CGRectMake(0, 0, 2*ZMScacle, h-50*ZMScacle);
    // 指针换成图片
//    secondLayer.bounds = CGRectMake(0, 0, 29*ZMScacle, 130*ZMScacle);
//    secondLayer.contents = (id)[UIImage imageNamed:@"zhizhen"].CGImage;
    layer = secondLayer;
    [self.bgImageView.layer addSublayer:secondLayer];
    
    
    CALayer *layer2 = [CALayer layer];
    layer2.backgroundColor = HEXCOLOR(0xff8069).CGColor;
    // 设置锚点
    layer2.anchorPoint = CGPointMake(0.5, 1);
    layer2.position = CGPointMake(w*0.5, h-10*ZMScacle);
    layer2.bounds = CGRectMake(0, 0, 12*ZMScacle, 12*ZMScacle);
    layer2.cornerRadius = 6*ZMScacle;
    [self.bgImageView.layer addSublayer:layer2];
    
    
    CALayer *layer3 = [CALayer layer];
    layer3.backgroundColor = [UIColor whiteColor].CGColor;
    // 设置锚点
    layer3.anchorPoint = CGPointMake(0.5, 1);
    layer3.position = CGPointMake(w*0.5, h-12*ZMScacle);
    layer3.bounds = CGRectMake(0, 0, 8*ZMScacle, 8*ZMScacle);
    layer3.cornerRadius = 4*ZMScacle;
    [self.bgImageView.layer addSublayer:layer3];
    
    layer.transform = CATransform3DMakeRotation(self.currentRadian, 0, 0, 1);
    
}

- (void)drawRect:(CGRect)rect {
    [self drawBg];
}

- (void) drawBg
{
    CGPoint center = CGPointMake(w*0.5, h-15*ZMScacle);
    CGFloat radius = self.frame.size.width/2-4*ZMScacle;
    CGFloat startA = 0;
    CGFloat endA = M_PI;
    
    
    
    // 内圈半环
    // 大
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:center];
    [path addArcWithCenter:center radius:radius startAngle:-M_PI_2 + self.currentRadian endAngle:endA clockwise:NO];
    [HEXCOLOR(0x23a7f1) set];
    [path fill];
    
    CGFloat bgEndAngle = -M_PI_2 + self.currentRadian;
    UIBezierPath *bgPath = [UIBezierPath bezierPath];
    [bgPath moveToPoint:center];
    [bgPath addArcWithCenter:center radius:radius startAngle:startA endAngle:bgEndAngle clockwise:NO];
    [HEXCOLOR(0xf1f1f1) set];
    [bgPath fill];
    
    // 小
    UIBezierPath *path2 = [UIBezierPath bezierPath];
    [path2 moveToPoint:center];
    [path2 addArcWithCenter:center radius:radius-9*ZMScacle startAngle:startA endAngle:endA clockwise:NO];
    self.backgroundColor ? [self.backgroundColor set] : [[UIColor whiteColor] set];
    [path2 stroke];
    [path2 fill];
    
    // 外圈line
    CGFloat radius2 = self.frame.size.width/2-1*ZMScacle;
    UIBezierPath *path3 = [UIBezierPath bezierPath];
    [path3 addArcWithCenter:center radius:radius2 startAngle:-M_PI_2 + self.currentRadian endAngle:endA clockwise:NO];
    [HEXCOLOR(0x23a7f1) set];
    [path3 stroke];
    
    
    UIBezierPath *bgPath2 = [UIBezierPath bezierPath];
    [bgPath2 addArcWithCenter:center radius:radius2 startAngle:startA endAngle:-M_PI_2 + self.currentRadian clockwise:NO];
    [HEXCOLOR(0xf1f1f1) set];
    [bgPath2 stroke];
    
    
}

- (void)handlePan:(UIPanGestureRecognizer *)gesture {
    CGPoint currentPosition = [gesture locationInView:self];
    
    if (gesture.state == UIGestureRecognizerStateChanged)
    {
//        NSLog (@"[%f,%f]",currentPosition.x, currentPosition.y);
        self.currentRadian = [self calculateRadian:currentPosition];
        [self setNeedsDisplay];
//        NSLog(@"%f", self.currentRadian);
        
        [self currentMonth];
    }
    
    // 动画
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    layer.transform = CATransform3DMakeRotation(self.currentRadian, 0, 0, 1);
    [CATransaction commit];
}

- (CGFloat)calculateRadian:(CGPoint)pos {
    
    if (pos.x == ZM_circle_X) {
        return 0;
    }
    if (pos.y > ZM_circle_Y  && pos.x <= ZM_circle_X) {
        return -M_PI_2;
    }
    if (pos.y > ZM_circle_Y  && pos.x > ZM_circle_X) {
        return M_PI_2;
    }
    
    CGFloat x_space = pos.x - ZM_circle_X;
    CGFloat y_space = ZM_circle_Y - pos.y;
    CGFloat r_space = sqrt(x_space*x_space + y_space*y_space);
    
    CGFloat result = M_PI_2 -  acos(x_space/r_space);
    
    //    NSLog(@"x_space: %f, y_space: %f,  r_space: %f", x_space,y_space,r_space);
    NSLog(@"result:------- %f", result);
    
    return result;
}

/*
- (CGFloat)calculateRadian: (CGPoint) pos
{
    CGPoint tmpPoint = CGPointMake(pos.x, [self center].y);
    
    // return zero if needle in center
    if (pos.x == [self center].x) {
        return 0;
    }
    
    if (pos.y > [self center].y) {
        return self.currentRadian;
    }
    
    // calculate distance between pos and center
    CGFloat p12 = [self calculateDistanceFrom:pos to:[self center]];
    
    // calculate distance between pos and tmpPoint
    CGFloat p23 = [self calculateDistanceFrom:pos to: tmpPoint];
    
    // cacluate distance between tmpPont and center
    CGFloat p13 = [self calculateDistanceFrom:tmpPoint to: [self center]];
    
    CGFloat result = M_PI_2 - acos(((p12 * p12) + (p13 * p13) - (p23 * p23))/(2 * p12 * p13));
    
    if (pos.x <= [self center].x) {
        result = -result;
    }
    
    if (result > (M_PI_2)) {
        return M_PI_2;
    }
    
    if (result < (-M_PI_2)) {
        return -M_PI_2;
    }
    
    //    NSLog(@"Calculated Angle: %f", result);
    
    return result;
}
- (CGFloat)calculateDistanceFrom: (CGPoint) p1 to: (CGPoint) p2
{
    CGFloat dx = p2.x - p1.x;
    CGFloat dy = p2.y - p1.y;
    CGFloat distance = sqrt(dx*dx + dy*dy);
    return distance;
}
 */

- (NSInteger)currentMonth {
    NSInteger month = -1;
    
    CGFloat monthSection = M_PI/(self.count-1);
    CGFloat currentSection = -M_PI_2 + monthSection/2;
    
    for (int i = 2; i <= self.count-1; i++) {
        if (self.currentRadian >= currentSection &&
            self.currentRadian <  (currentSection + monthSection)) {
            month = i;
            break;
        }
        currentSection += monthSection;
    }
    
    if (self.currentRadian >= (M_PI_2-monthSection/2)) {
        month = self.count + 5;
    }
    
    if (self.currentRadian <= -(M_PI_2-monthSection/2)) {
        month = self.count - 12;
    }
//    NSLog(@"%lu", (unsigned long)month);
    _countLab.text = [NSString stringWithFormat:@"%lu 月", month];
    if (self.ZMGaugeViewBlock) {
        self.ZMGaugeViewBlock(month);
    }
    
    return month;
}

@end
